package io.renren.modules.sys.controller;


import com.alipay.api.internal.util.AlipaySignature;
import io.renren.common.utils.R;
import io.renren.common.config.AlipayConfig;
import io.renren.modules.order.controller.OrderController;
import io.renren.modules.order.entity.OrderEntity;
import io.renren.modules.sys.service.Test2Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@RestController
//@RequestMapping("api/test2")
@RequestMapping(value = "api/getAlipayNotify", produces = "application/json;charset=UTF-8", method = {
        RequestMethod.GET, RequestMethod.POST })
public class AliCallBackController {
    @Autowired
    Test2Service service;
    @Autowired
    OrderController orderController;
    /**
     */
    @PostMapping("bbb")
    public R getAlipayNotify(HttpServletRequest request) {
        Map<String, String> params = new HashMap<String, String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 乱码解决，这段代码在出现乱码时使用。
            // valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        // 切记alipaypublickey是支付宝的公钥，请去open.alipay.com对应应用下查看。
        try {
            boolean flag = AlipaySignature.rsaCheckV1(params, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.CHARSET,
                    AlipayConfig.SIGN_TYPE);
            if (flag) {
                String trade_status = params.get("trade_status");
                String OrderNum = params.get("out_trade_no");  //订单号
                String trade_no = params.get("trade_no");
                if ("TRADE_SUCCESS".equals(trade_status)) { // 交易支付成功的执行相关业务逻辑
                    //根据订单号修改成已付款
                    service.updateOrderStatusByOrderNum(OrderNum);
                    String payType = OrderNum.substring(OrderNum.length() - 1);//   获得交易的类型
                    /*if (payType.equals("1")){ //支付类型1 课程
                        System.out.println("购买课程");

                    }else if (payType.equals("2")){ //2 拼考（发起拼考）
                        System.out.println("发起拼考");
                        //

                    }else if (payType.equals("3")){ //3 拼考（加入拼考）

                    }else if (payType.equals("4")){ //4 将订单改成已付款

                    }*/
                    OrderEntity orderEntity = new OrderEntity();
                    orderEntity.setStatus("已付款");
                    orderEntity.setOrderId(OrderNum);
                    orderController.updateOrder(orderEntity);
                } else if ("TRADE_CLOSED".equals(trade_status)) { // 未付款交易超时关闭,或支付完成后全额退款,执行相关业务逻辑
                    OrderEntity orderEntity = new OrderEntity();
                    orderEntity.setStatus("交易关闭");
                    orderEntity.setOrderId(OrderNum);
                    orderController.updateOrder(orderEntity);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.ok("ccc",100).put("data","ddddd");
    }


//    @RequestMapping("aaa1")
//    @ResponseBody
//    public String getUserNameByMobile111(Map<String, String> mobile) {
//        return "aaa1";
//    }

}
